package com.alks.function.service.impl;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.utils.MD5Utils;
import com.alks.common.utils.UserInfoUtil;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.stringUtils.ZStringUtils;
import com.alks.entity.data.entity.PcStitchWorkerRep;
import com.alks.entity.data.entity.PcStitchWorkerReq;
import com.alks.entity.data.entity.SdUser;
import com.alks.entity.data.entity.sys.SysUser;
import com.alks.entity.data.enums.ResultCodeEnum;
import com.alks.entity.data.page.PageRecord;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.sys.SdUserDto;
import com.alks.function.data.request.sys.SdUserAddRequest;
import com.alks.function.data.request.sys.SdUserRequest;
import com.alks.function.data.request.sys.SdUserUpdateRequest;
import com.alks.function.mapper.SdUserMapper;
import com.alks.function.mapper.system.SYS_SdPrgPrivilegeMapper;
import com.alks.function.service.SdUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
@Service
public class SdUserServiceImpl extends ServiceImpl<SdUserMapper, SdUser> implements SdUserService {

    @Autowired
    private SdUserMapper sdUserMapper;

    @Autowired
    private SysUserServiceImpl sysUserServiceImpl;

    /**
     * 分页查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getUser(SdUserRequest request) {
        PageRecord<SdUserDto> list = new PageRecord<>();
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        List<SdUserDto> user = sdUserMapper.getUser(request, companyId);
        list.setList(user);
        PageInfo pageInfo = new PageInfo(user);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 修改
     * @param request
     * @return
     */
    @Override
    public ResponseInfo updateUser(SdUserUpdateRequest request) {
        if (ObjectUtils.isEmpty(request.getUserId())){
            throw new ServiceErrorException("用户id不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getEngName())){
            throw new ServiceErrorException("英文名字不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getChiName())){
            throw new ServiceErrorException("中文名字不能为空!");
        }
        SdUser sdUser = new SdUser();
        BeanUtil.copyProperties(request,sdUser);
        LambdaUpdateWrapper<SdUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SdUser::getUserId,request.getUserId());
        sdUserMapper.update(sdUser,wrapper);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    @Override
    public ResponseInfo updatePwd(String userId) {
        if (ObjectUtils.isEmpty(userId)){
            throw new ServiceErrorException("用户id不能为空!");
        }
        SdUser sdUser = new SdUser();
        String salt = RandomStringUtils.random(6, true, true);
        sdUser.setSalt(salt);
        sdUser.setUserId(userId);
        salt="123"+salt;
        String passWord = MD5Utils.md5(salt);
        sdUser.setPassword(passWord);
        LambdaUpdateWrapper<SdUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SdUser::getUserId,userId);
        sdUserMapper.update(sdUser,wrapper);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 修改密码
     * @param userId
     * @return
     */
    @Override
    public ResponseInfo updatePassword(String userId, String oldPassword, String newPassword) {
        if (ObjectUtils.isEmpty(userId)){
            throw new ServiceErrorException("用户id不能为空!");
        }
        if (ObjectUtils.isEmpty(oldPassword)){
            throw new ServiceErrorException("旧密码不能为空!");
        }
        if (ObjectUtils.isEmpty(newPassword)){
            throw new ServiceErrorException("新密码不能为空!");
        }
        SdUser sdUser = sdUserMapper.selectById(userId);
        if (ObjectUtils.isEmpty(sdUser)){
            throw new ServiceErrorException("用户不存在!");
        }
        // 检查新密码是否包含特殊字符
        System.out.println("oldPassword: "+ oldPassword);
        System.out.println("newPassword: "+ newPassword);
        if (containsSpecialCharacters(newPassword)) {
            throw new ServiceErrorException("密码不能包含特殊字符，如：[空格、\\、'、\"、%、#、<、>、+]");
        }

        String salt = sdUser.getSalt();
        String oldpassWord = MD5Utils.md5(oldPassword+salt);
        if (!oldpassWord.equals(sdUser.getPassword())){
            throw new ServiceErrorException("旧密码错误!");
        }
        String passWord = MD5Utils.md5(newPassword+salt);
        if (oldpassWord.equals(passWord)){
            throw new ServiceErrorException("新密码不能与旧密码相同!");
        }

        //判断密码
        ResponseInfo simplePassword = sysUserServiceImpl.isSimplePassword(newPassword);
        if (simplePassword.getCode() != 200){
            return ResponseInfo.error(simplePassword.getMessage());
        }

        sdUser.setPassword(passWord);
        LambdaUpdateWrapper<SdUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SdUser::getUserId,userId);
        sdUserMapper.update(sdUser,wrapper);
        return ResponseInfo.ok("操作成功!");
    }

    @Override
    public ResponseInfo workName(String workId) {
        Map<String,Object> workName = sdUserMapper.getWorkName(workId);
        if (workName==null)return ResponseInfo.error("该工号不存在!");
        return ResponseInfo.ok(workName);
    }

    /**
     * @param engName
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @Override
    public ResponseInfo updatePasswordLogin(String engName, String oldPassword, String newPassword) {
        if (ObjectUtils.isEmpty(engName)){
            throw new ServiceErrorException("用户名不能为空!");
        }
        if (ObjectUtils.isEmpty(oldPassword)){
            throw new ServiceErrorException("旧密码不能为空!");
        }
        if (ObjectUtils.isEmpty(newPassword)){
            throw new ServiceErrorException("新密码不能为空!");
        }

        //根据用户名字取用户ID
        SysUser sysUser = new SysUser();
        sysUser.setLoginName(engName);
        String username = sysUser.getLoginName().toUpperCase();
        SdUser baseSysUser = lambdaQuery().eq(SdUser::getEngName, username).one();
        String userId = baseSysUser.getUserId();

        SdUser sdUser = sdUserMapper.selectById(userId);
        if (ObjectUtils.isEmpty(sdUser)){
            throw new ServiceErrorException("用户不存在!");
        }

        String salt = sdUser.getSalt();
        String oldpassWord = MD5Utils.md5(oldPassword+salt);
        if (!oldpassWord.equals(sdUser.getPassword())){
            throw new ServiceErrorException("旧密码错误!");
        }
        String passWord = MD5Utils.md5(newPassword+salt);
        if (oldpassWord.equals(passWord)){
            throw new ServiceErrorException("新密码不能与旧密码相同!");
        }

        //判断密码
        ResponseInfo simplePassword = sysUserServiceImpl.isSimplePassword(newPassword);
        if (simplePassword.getCode() != 200){
            return ResponseInfo.error(simplePassword.getMessage());
        }

        sdUser.setPassword(passWord);
        //LambdaUpdateWrapper<SdUser> wrapper = new LambdaUpdateWrapper<>();
        //wrapper.eq(SdUser::getUserId,userId);
        //sdUserMapper.update(sdUser,wrapper);
        //根据ID修改密码(仅修改密码)
        sdUserMapper.updatePassword(sdUser);
        return ResponseInfo.ok("操作成功!");
    }


    /**
     * 添加用户
     * @param request
     * @return
     */
    @Override
    public ResponseInfo addUser(SdUserAddRequest request) {
        if (ObjectUtils.isEmpty(request.getEngName())){
            throw new ServiceErrorException("英文名字不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getChiName())){
            throw new ServiceErrorException("中文名字不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getPosId())){
            throw new ServiceErrorException("请选择职务!");
        }
        if (ObjectUtils.isEmpty(request.getDeptNo())){
            throw new ServiceErrorException("请选择部门!");
        }
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        LambdaQueryWrapper<SdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SdUser::getEngName,request.getEngName());
        SdUser user = sdUserMapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(user)){
            throw new ServiceErrorException("英文名字已存在!");
        }
        SdUser sdUser = new SdUser();
        BeanUtil.copyProperties(request,sdUser);
        String salt = RandomStringUtils.random(6, true, true);
        sdUser.setSalt(salt);
        salt="123"+salt;
        String passWord = MD5Utils.md5(salt);
        sdUser.setPassword(passWord);
        sdUser.setUserId(request.getEngName());
        sdUser.setFactory("荣信");
        sdUser.setCompanyId(companyId);
        sdUserMapper.insert(sdUser);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 删除
     * @param userId
     * @return
     */
    @Override
    public ResponseInfo delUser(String userId) {
        if (ObjectUtils.isEmpty(userId)){
            throw new ServiceErrorException("用户id不能为空!");
        }
        sdUserMapper.delUser(userId);
        return ResponseInfo.ok("操作成功!");
    }


    @Override
    @AutoPageAop
    public ResponseInfo workerList(PcStitchWorkerReq req) {
        Map<String, Object> map = new HashMap<>();
        List<PcStitchWorkerRep> list = sdUserMapper.workerList(req);
        Page<PcStitchWorkerRep> page = (Page<PcStitchWorkerRep>) list;
        map.put("list",list);
        map.put("page",page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo insertWorker(PcStitchWorkerRep req) {
        List<String> ids = sdUserMapper.getIds();
        if (ids.contains(req.getWorkerId())) return ResponseInfo.error("id已存在");
        req.setCompanyId(UserInfoUtil.getUserInfo().getCompanyId());
        sdUserMapper.insertIntoStitchWorker(req);
        return ResponseInfo.ok("添加成功");
    }

    @Override
    public ResponseInfo deleteStitchWorkersByIds(List<String> ids) {
        List<String> oldIds = sdUserMapper.getUseIds();
        for (String id : ids) {
            if (oldIds.contains(id)) return ResponseInfo.error("删除失败。。。绿色用户不允许被删除");
        }
        Integer num = sdUserMapper.deleteStitchWorkersByIds(ids);
        if (num<=0) return  ResponseInfo.error("删除失败");
        return ResponseInfo.ok("删除成功");
    }

    @Override
    public ResponseInfo updateStitchWorker(List<String> ids, String line) {
        if (line == null||"".equals(line)) return ResponseInfo.error("线别不能为空");
        if (ZStringUtils.isEmpty(ids)) return ResponseInfo.error("请勾选员工");
        Integer num = sdUserMapper.updateStitchWorker(ids,line);
        if (num<=0) return  ResponseInfo.error("删除失败");
        return ResponseInfo.ok("修改成功");
    }
    /**
     * 检查字符串是否包含不允许的特殊字符
     * @param str 待检查的字符串
     * @return 如果包含不允许的字符返回true，否则返回false
     */
    private boolean containsSpecialCharacters(String str) {
        // 定义不允许使用的特殊字符的正则表达式模式
        // 注意这里的转义字符
        String disallowedCharsPattern = "[\\s" +    // 空白字符
                "\\\\" +    // 反斜杠 (\)
                "'\"%" +    // 单引号 (')、双引号 (")、百分号 (%)
                "#<>\\+]";  // 井号 (#)、小于号 (<)、大于号 (>)、加号 (+)
        Pattern pattern = Pattern.compile(disallowedCharsPattern);
        return pattern.matcher(str).find();
    }

}
